﻿using System.Globalization;
using Pap.Data;
using Utils.UIPermission;

namespace Pap.Web.Modules.Loan.Views
{
    using System;
    using System.Web.UI;

    using Coolite.Ext.Web;

    using Pap.Web.Modules.Loan.ViewModel;
    using Pap.Web.Utils;

    /// <summary>
    /// 
    /// </summary>
    public partial class InstallmentsPayment : BasePage<InstallmentsPaymentViewModel>, IPermittedPage
    {
        #region [ Properties ]

        /// <summary>
        /// Gets the execution ID.
        /// </summary>
        private string InstallmentId
        {
            get
            {
                return Request.QueryString["InstallmentID"];
            }
        }

        #endregion Properties

        #region [ Events ]

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Ext.IsAjaxRequest && !Page.IsPostBack)
            {
                if (!InstallmentId.IsNullOrEmpty())
                {
                    FillInstallmentData(InstallmentId.ToGuid());
                    if (this.ViewModel.IsAutomaticReceipteMode())
                    {
                        txtReceiptNumber.Hide();
                        txtReceiptNumber.AllowBlank = true;
                    }
                    else
                    {
                        txtReceiptNumber.Show();
                        txtReceiptNumber.AllowBlank = false;
                    }
                }
            }
        }

        /// <summary>
        /// Handles the Changed event of the TxtPaymentAmount control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void TxtPaymentAmount_Changed(object sender, AjaxEventArgs e)
        {
            txtChangeAmount.Text = (Convert.ToDouble(txtDueAmount.Value) - Convert.ToDouble(txtPaymentAmount.Value)).ToString();
        }

        /// <summary>
        /// Handles the Clicked event of the BtnPay control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnPay_Clicked(object sender, AjaxEventArgs e)
        {
            if (!InstallmentId.IsNullOrEmpty())
            {
                if (Convert.ToDouble(txtPaymentAmount.Value) > 0)
                {
                    var receipt = this.ViewModel.PayInstallment(InstallmentId.ToGuid(),
                                                                Convert.ToDouble(txtPaymentAmount.Value),
                                                                txtReceiptNumber.Text,
                                                                DateTime.ParseExact(txtPaymentDate.Text, "dd/MM/yyyy",
                                                                                    CultureInfo.CurrentCulture));

                    wndGenerateRecipteNumber.LoadContent(string.Format("~/Loan.route/Receipt?CustomerName={0}&LoanNumber={1}&ReceipteNumber={2}&ReceiptDate={3}&ReceiptAmount={4}",
                                                                 txtCustomerName.Text, txtLoanNumber.Text, receipt.ReceiptNumber, receipt.ReceiptDate.ToString("dd-MM-yyyy"), receipt.ReceiptAmount));
                    wndGenerateRecipteNumber.Show();
                }

            }
        }

        /// <summary>
        /// Handles the Clicked event of the BtnCloseReceipte control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnCloseReceipte_Clicked(object sender, AjaxEventArgs e)
        {
            wndGenerateRecipteNumber.Hide();
            FillInstallmentData(InstallmentId.ToGuid());
        }

        /// <summary>
        /// Handles the Clicked event of the btnClose control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void btnClose_Clicked(object sender, AjaxEventArgs e)
        {
            this.RedirectToPreviousPage();
        }

        /// <summary>
        /// Handles the Clicked event of the BtnOldDate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnOldDate_Clicked(object sender, AjaxEventArgs e)
        {
            wndOldPayment.Show();
        }

        /// <summary>
        /// Handles the Clicked event of the BtnSubmitOldDate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void BtnSubmitOldDate_Clicked(object sender, AjaxEventArgs e)
        {
            txtPaymentDate.Text = dateOldDate.SelectedDate.ToString("dd/MM/yyyy");
            this.wndOldPayment.Hide();
        }

        #endregion

        #region [ Methods ]
        /// <summary>
        /// Fills the installment data.
        /// </summary>
        /// <param name="installmentId">The installment Id.</param>
        private void FillInstallmentData(Guid installmentId)
        {
            var installment = this.ViewModel.GetLoanInstallment(installmentId);

            txtCustomerName.Text = installment.LoanExecution.CustomerLoan.CustomerObj.CustomerName;
            txtCustomerSSN.Text = installment.LoanExecution.CustomerLoan.CustomerObj.SSN;
            txtLoanNumber.Text = installment.LoanExecution.CustomerLoan.LoanNumber.ToString();
            txtPaymentDate.Text = DateTime.Today.ToString("dd/MM/yyyy");
            txtPeneltyAmount.Text = installment.PenaltyAmount.ToString();
            txtInstallmentDueDate.Text = installment.InstallmentDate.ToString("dd/MM/yyyy");

            storePaymentsHistory.DataSource = this.ViewModel.GetLoanExcutionPayments(installment);
            storePaymentsHistory.DataBind();

            var totalDueAount = this.ViewModel.GetLoanDueAmount(installment);
            txtDueAmount.Text = totalDueAount.ToString();

             Nullable<DateTime> oldDate = this.ViewModel.GetOldDate(installment);
             if (oldDate != null)
                 txtPaymentDate.Text = string.Format("{0:dd/MM/yyyy}", oldDate);
             else
                 txtPaymentDate.Text = string.Format("{0:dd/MM/yyyy}", Pap.Web.Utils.Extentions.ProcessDate);

             if (totalDueAount > 0)
             {
                 txtPaymentAmount.MaxValue = totalDueAount;
             }
             else
             {
                 this.txtPaymentAmount.Disabled =
                     this.btnPay.Disabled = true;
             }
            dateOldDate.MaxDate = DateTime.Now;


            txtPaymentAmount.Reset();
            txtReceiptNumber.Reset();
        }
        #endregion

        public string PermissionName
        {
            get { return Permissions.InstallmentsPayment.ToString(); }
        }
    }
}